#include "globalpagemanager.h"
#include "customfilebrowser.h"
#include "mainwindow.h"
#include <QDebug>
// 静态成员变量定义
std::unique_ptr<GlobalPageManager> GlobalPageManager::m_instance = nullptr;
QMutex GlobalPageManager::m_mutex;
GlobalPageManager::GlobalPageManager(QObject* parent)
    : QObject(parent)
{
}
GlobalPageManager& GlobalPageManager::instance()
{
    QMutexLocker locker(&m_mutex);
    if (!m_instance) {
        m_instance = std::make_unique<GlobalPageManager>();
    }
    return *m_instance;
}
void GlobalPageManager::destroyInstance()
{
    QMutexLocker locker(&m_mutex);
    if (m_instance) {
        m_instance.reset();
    }
}
GlobalPageManager* GlobalPageManager::getInstance()
{
    return &instance();
}
// === 全局页码状态管理 ===
void GlobalPageManager::setCurrentGlobalPage(int globalPage)
{
    if (globalPage < 0) {
        return;
    }
    if (globalPage > m_totalGlobalPages && m_totalGlobalPages > 0) {
        globalPage = m_totalGlobalPages;
    }
    if (m_currentGlobalPage != globalPage) {
        int oldPage = m_currentGlobalPage;
        m_currentGlobalPage = globalPage;
        emit globalPageChanged(globalPage);
    }
}
void GlobalPageManager::updateTotalPages(int totalPages)
{
    // ⚠️ 此方法已废弃！会导致数据不一致！
    // 不要使用此方法，应该使用 recalculatePageMappings()
    qWarning() << "[GlobalPageManager] ⚠️ updateTotalPages已废弃！直接设置总页数会导致数据不一致";
    qWarning() << "[GlobalPageManager] ⚠️ 应该调用 recalculatePageMappings() 或让 CustomFileBrowser 重新计算";
    
    if (totalPages < 0) {
        return;
    }
    if (m_totalGlobalPages != totalPages) {
        int oldTotal = m_totalGlobalPages;
        m_totalGlobalPages = totalPages;
        emit totalGlobalPagesChanged(totalPages);
        qWarning() << "[GlobalPageManager] ⚠️ 总页数被直接修改（不推荐）:" << oldTotal << "->" << totalPages;
    }
}
// === 文件页码映射计算 ===

// ========== 类型安全API实现 ==========

std::optional<PageNumberV2::GlobalPageContext> GlobalPageManager::getPageContext(
    const QString& fileIdentity,
    PageNumberV2::ArrayIndex fileArrayIndex
) const {
    // 查找文件起始页
    auto it = m_fileStartPages.find(fileIdentity);
    if (it == m_fileStartPages.end()) {
        return std::nullopt;
    }
    
    PageNumberV2::PageNumber startPage = it.value();
    
    
    // 使用工具函数生成上下文
    return PageNumberV2::makeGlobalContext(fileArrayIndex, startPage, m_totalGlobalPages);
}

std::optional<PageNumberV2::PageNumber> GlobalPageManager::getFileStartPageNumber(
    const QString& fileIdentity
) const {
    auto it = m_fileStartPages.find(fileIdentity);
    if (it == m_fileStartPages.end()) {
        return std::nullopt;
    }
    return it.value();
}

// ========== 便捷方法（兼容int返回值） ==========

QPair<int, int> GlobalPageManager::getFileGlobalRange(const QString& fileIdentity) const
{
    auto startPageOpt = getFileStartPageNumber(fileIdentity);
    if (!startPageOpt.has_value()) {
        return {0, 0};
    }
    int startPage = startPageOpt->value();
    int displayPages = m_fileDisplayPages.value(fileIdentity, 1);
    int endPage = startPage + displayPages - 1;
    return {startPage, endPage};
}
int GlobalPageManager::convertToGlobalPage(const QString& fileIdentity, int localPage) const
{
    // 使用新的类型安全API
    auto context = getPageContext(fileIdentity, PageNumberV2::ArrayIndex(localPage));
    if (!context.has_value()) {
        return 0;  // 文件不存在
    }
    
    return context->currentPageValue();
}
int GlobalPageManager::convertToLocalPage(const QString& fileIdentity, int globalPage) const
{
    auto range = getFileGlobalRange(fileIdentity);
    if (range.first == 0) {
        return -1;  // 文件不存在
    }
    int startPage = range.first;
    int endPage = range.second;
    if (globalPage < startPage || globalPage > endPage) {
        return -1;  // 超出范围
    }
    return globalPage - startPage;  // 返回文件内索引
}

int GlobalPageManager::getFileStartPage(const QString& fileIdentity) const
{
    auto startPageOpt = getFileStartPageNumber(fileIdentity);
    if (!startPageOpt.has_value()) {
        return 0;  // 文件不存在
    }
    return startPageOpt->value();
}

void GlobalPageManager::setPageNumberStartOffset(int startOffset)
{
    if (startOffset < 1) {
        startOffset = 1;
    }
    if (m_pageNumberStartOffset != startOffset) {
        m_pageNumberStartOffset = startOffset;
        // 发出页码偏移变化信号，通知所有相关组件更新
        emit pageNumberStartOffsetChanged(startOffset);
    }
}

int GlobalPageManager::getPageNumberStartOffset() const
{
    return m_pageNumberStartOffset;
}
// === 文件排序和状态更新 ===
void GlobalPageManager::updateFileInfo(const QString& fileIdentity, int displayPages)
{
    if (displayPages <= 0) {
        displayPages = 1;
    }
    bool isNewFile = !m_fileDisplayPages.contains(fileIdentity);
    // === 关键修复：正确获取旧页数，避免新文件不触发重算的bug ===
    int oldDisplayPages = isNewFile ? 0 : m_fileDisplayPages.value(fileIdentity, 0);
    
    
    m_fileDisplayPages[fileIdentity] = displayPages;
    // 如果是新文件，添加到有序列表中（如果不在列表中）
    if (isNewFile && !m_orderedFileIdentities.contains(fileIdentity)) {
        m_orderedFileIdentities.append(fileIdentity);
    }
    // 如果页数发生变化或是新文件，重新计算映射
    if (isNewFile || oldDisplayPages != displayPages) {
        recalculatePageMappings();
    } else {
    }
}
void GlobalPageManager::clearAllFileInfo()
{
    m_fileDisplayPages.clear();
    m_fileStartPages.clear();
    m_orderedFileIdentities.clear();
    m_currentGlobalPage = 0;
    m_totalGlobalPages = 0;
    emit pageMappingsChanged();
    emit totalGlobalPagesChanged(0);
}
void GlobalPageManager::removeFileInfo(const QString& fileIdentity)
{
    if (m_fileDisplayPages.contains(fileIdentity)) {
        m_fileDisplayPages.remove(fileIdentity);
        m_fileStartPages.remove(fileIdentity);
        m_orderedFileIdentities.removeAll(fileIdentity);
        recalculatePageMappings();
    }
}
void GlobalPageManager::recalculatePageMappings()
{
    recalculateMappings();
    emit pageMappingsChanged();
}
// === 调试和状态查询 ===
QString GlobalPageManager::getDebugInfo() const
{
    QString info;
    QTextStream stream(&info);
    stream << "=== GlobalPageManager 调试信息 ===" << Qt::endl;
    stream << "当前全局页码: " << m_currentGlobalPage << Qt::endl;
    stream << "全局总页数: " << m_totalGlobalPages << Qt::endl;
    stream << "文件数量: " << m_fileDisplayPages.size() << Qt::endl;
    stream << Qt::endl;
    stream << "文件页码映射:" << Qt::endl;
    for (const QString& fileIdentity : m_orderedFileIdentities) {
        int displayPages = m_fileDisplayPages.value(fileIdentity, 0);
        auto startPageOpt = getFileStartPageNumber(fileIdentity);
        int startPage = startPageOpt.has_value() ? startPageOpt->value() : 0;
        int endPage = startPage + displayPages - 1;
        stream << QString("  %1: 页数 %2, 范围 %3-%4")
                  .arg(fileIdentity.right(20))
                  .arg(displayPages)
                  .arg(startPage)
                  .arg(endPage);
    }
    return info;
}
QPair<bool, QString> GlobalPageManager::validatePageMappings() const
{
    QStringList errors;
    // 检查全局页码有效性
    if (m_currentGlobalPage < 0 || m_currentGlobalPage > m_totalGlobalPages) {
        errors.append(QString("无效的全局页码: %1/%2")
                     .arg(m_currentGlobalPage).arg(m_totalGlobalPages));
    }
    // 检查文件映射一致性
    int calculatedTotal = 0;
    for (const QString& fileIdentity : m_orderedFileIdentities) {
        int displayPages = m_fileDisplayPages.value(fileIdentity, 0);
        auto startPageOpt = getFileStartPageNumber(fileIdentity);
        int startPage = startPageOpt.has_value() ? startPageOpt->value() : 0;
        if (displayPages <= 0) {
            errors.append(QString("文件 %1 无效的显示页数: %2")
                         .arg(fileIdentity).arg(displayPages));
        }
        if (startPage != calculatedTotal + 1) {
            errors.append(QString("文件 %1 起始页码错误: 期望 %2, 实际 %3")
                         .arg(fileIdentity).arg(calculatedTotal + 1).arg(startPage));
        }
        calculatedTotal += displayPages;
    }
    // 检查总页数一致性
    if (calculatedTotal != m_totalGlobalPages) {
        errors.append(QString("总页数不一致: 计算 %1, 存储 %2")
                     .arg(calculatedTotal).arg(m_totalGlobalPages));
    }
    bool isValid = errors.isEmpty();
    QString errorMessage = errors.isEmpty() ? "验证通过" : errors.join("; ");
    return {isValid, errorMessage};
}
// === 私有方法 ===
void GlobalPageManager::recalculateMappings()
{
    
    // === 关键修复：清理 m_orderedFileIdentities 中不在 m_fileDisplayPages 中的文件 ===
    // 这可能是导致页码跳跃的根本原因
    QList<QString> invalidFiles;
    for (const QString& fileIdentity : m_orderedFileIdentities) {
        if (!m_fileDisplayPages.contains(fileIdentity)) {
            invalidFiles.append(fileIdentity);
        }
    }
    
    if (!invalidFiles.isEmpty()) {
        qWarning() << "[GlobalPageManager] 发现" << invalidFiles.size() << "个无效文件（在有序列表中但不在页数映射中）";
        for (const QString& file : invalidFiles) {
            qWarning() << "[GlobalPageManager] 移除无效文件:" << file.right(40);
            m_orderedFileIdentities.removeAll(file);
        }
    }
    
    // === 关键修复2：清理 m_fileDisplayPages 中不在 m_orderedFileIdentities 中的文件 ===
    QList<QString> orphanedFiles;
    for (auto it = m_fileDisplayPages.begin(); it != m_fileDisplayPages.end(); ++it) {
        if (!m_orderedFileIdentities.contains(it.key())) {
            orphanedFiles.append(it.key());
        }
    }
    
    if (!orphanedFiles.isEmpty()) {
        qWarning() << "[GlobalPageManager] 发现" << orphanedFiles.size() << "个孤立文件（在页数映射中但不在有序列表中）";
        for (const QString& file : orphanedFiles) {
            qWarning() << "[GlobalPageManager] 移除孤立文件:" << file.right(40);
            m_fileDisplayPages.remove(file);
            m_fileStartPages.remove(file);  // 同时清理startPages映射
        }
    }
    
    // 验证总页数计算
    int calculatedTotal = 0;
    for (auto it = m_fileDisplayPages.begin(); it != m_fileDisplayPages.end(); ++it) {
        calculatedTotal += it.value();
    }
    
    // 输出当前文件顺序
    for (int i = 0; i < m_orderedFileIdentities.size(); ++i) {
        QString fileIdentity = m_orderedFileIdentities[i];
        int displayPages = m_fileDisplayPages.value(fileIdentity, 0);
    }
    
    m_fileStartPages.clear();
    int currentPage = 1;
    // 按文件顺序重新计算起始页码
    for (int i = 0; i < m_orderedFileIdentities.size(); ++i) {
        const QString& fileIdentity = m_orderedFileIdentities[i];
        int displayPages = m_fileDisplayPages.value(fileIdentity, 0);
        if (displayPages > 0) {
            // 使用PageNumber类型存储
            m_fileStartPages[fileIdentity] = PageNumberV2::PageNumber(currentPage);
            int endPage = currentPage + displayPages - 1;
            emit fileRangeChanged(fileIdentity, currentPage, endPage);
            currentPage += displayPages;
        } else {
            qWarning() << "[GlobalPageManager] 跳过文件" << i << "（页数为0）:" << fileIdentity.right(40);
        }
    }
    int totalPages = currentPage - 1;
    
    // 直接设置正确的总页数，确保与页码映射一致
    if (m_totalGlobalPages != totalPages) {
        int oldTotal = m_totalGlobalPages;
        m_totalGlobalPages = totalPages;
        emit totalGlobalPagesChanged(totalPages);
    }
}
void GlobalPageManager::updateTotalGlobalPages()
{
    int newTotal = 0;
    for (int displayPages : m_fileDisplayPages) {
        newTotal += displayPages;
    }
    if (m_totalGlobalPages != newTotal) {
        int oldTotal = m_totalGlobalPages;
        m_totalGlobalPages = newTotal;
        emit totalGlobalPagesChanged(newTotal);
    }
}
bool GlobalPageManager::isValidGlobalPage(int globalPage) const
{
    return globalPage >= 1 && globalPage <= m_totalGlobalPages;
}
void GlobalPageManager::onFileListChanged()
{
    // 响应文件列表变化，重新计算页码映射
    recalculatePageMappings();
}